/* @flow */

import { parse } from './parser/index'
import { optimize } from './optimizer'
import { generate } from './codegen/index'
import { createCompilerCreator } from './create-compiler'

// `createCompilerCreator` allows creating compilers that use alternative
// parser/optimizer/codegen, e.g the SSR optimizing compiler.
// Here we just export a default compiler using the default parts.
export const createCompiler = createCompilerCreator(function baseCompile(
  template: string,
  options: CompilerOptions
): CompiledResult {
  // 编译template为ast抽象语法树
  const ast = parse(template.trim(), options)
  if (options.optimize !== false) {
    /**
     * 优化ast抽象语法树
     * 1. 标记静态节点: 不包含动态内容的节点
     * 2. 标记静态根节点: 不包含动态内容且含义子标签的节点
     */
    optimize(ast, options)
  }
  /**
   * 生成字符串形式的render函数与staticRenderFns函数数组，staticRenderFns便于使用缓存作为优化方式
   * const code = ast ? genElement(ast, state) : '_c("div")'
   */
  const code = generate(ast, options)
  return {
    ast,
    render: code.render,
    staticRenderFns: code.staticRenderFns
  }
})
